package com.tensquare.search.service;

import com.tensquare.search.dao.ArticleDao;
import com.tensquare.search.pojo.Article;
import entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
import utils.IdWorker;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by WF on 2020/7/24 15:22
 */
@Service
public class ArticleService {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private ArticleDao articleDao;

    //1.添加文章
    public void add(Article article) {
        //1.1)设置文章的id
        article.setId(idWorker.nextId() + "");
        //1.2)添加文章到索引库中
        articleDao.save(article);
    }
    //2.根据关键字查询
    public PageResult<Article> search(String keywords, int page, int size) {
        //2.1)根据标题和内容查询文章
        Page<Article> articlePage = articleDao.findByTitleOrContentLike(keywords, keywords, PageRequest.of(page - 1, size));
        //2.2)返回pageREsult
        return new PageResult<>(articlePage.getTotalElements(),articlePage.getContent());
    }
    //3.查询列表
    public List<Article> findAll() {
          List<Article> articles = new ArrayList<>();
          articleDao.findAll().forEach(article->{
              articles.add(article);
          });
          return articles;
    }
}
